package glass;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;

import javax.swing.JPanel;

public class Missile extends JPanel implements Runnable{
	
	private int x, y;
	
	private final int DELAY = 50;
	private Thread animator;
	private Graphics graph;
	public Glass glass;
	
	public Missile(){
		setBackground(Color.BLACK);
		setDoubleBuffered(true);
		
		x = y = 10;
		
		
	}
	
	public Missile(Glass gl){
		setBackground(Color.BLACK);
		//setDoubleBuffered(true);
		
		glass = gl;
	}
	
	public Missile(Graphics g){
		//setBackground(Color.BLACK);
		//setDoubleBuffered(true);
		
		x = 10;
		graph = g;
		y = 10;
		
	}
	
	public void addNotify() {
        super.addNotify();
        animator = new Thread(this);
        animator.start();
    }
	
	public void setGraphics(Graphics g){
		graph = g;
	}
	
/*	public void paint(Graphics g){
		//super.paint(g);
		//g = glass.getGraphics();
		g = graph;
		
		Graphics2D g2d = (Graphics2D)g;
		g2d.setColor(Color.RED);
		g2d.fillRect(x, y, 10, 10);
		Toolkit.getDefaultToolkit().sync();
        g.dispose();
		
	}
*/	
	public void cycle() {
		x++; y++;
		
		if (y > 240) {
			y = -45;
			x = -45;
		}
	}
	
	public void run(){
		long beforeTime, timeDiff, sleep;

        beforeTime = System.currentTimeMillis();

        while (true) {

            
            if (glass != null){
            	cycle();
            	glass.posx = x;
            	glass.posy = y;
            	glass.repaint();
            }
            
            

            timeDiff = System.currentTimeMillis() - beforeTime;
            sleep = DELAY - timeDiff;

            if (sleep < 0)
                sleep = 2;
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                System.out.println("interrupted");
            }

            beforeTime = System.currentTimeMillis();
        }
	}
	
	
	
	
}
